﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using elmah2.core.interfaces;
using elmah2.core.data;
using System.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Xml;
using elmah2.core.encoders;
using System.Data;
using elmah2.core.loggers;

namespace elmah2.SqlServer
{
  [Serializable]
  public class SqlLogger : DBLogger, IErrorLogger
  {
    public override IDbCommand GetCommand()
    {
      return new SqlCommand();
    }

    public override IDbConnection GetConnection()
    {
      return new SqlConnection(_connectionString);
    }

    public override IDbCommand GetErrorsCommand(int page, int numPerPage, int? app)
    {
      ErrorData toReturn = new ErrorData();

      SqlCommand command = new SqlCommand();
      command.CommandText = "SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY TimeUtc DESC) AS Row, * FROM (SELECT	err.*,(SELECT COUNT(*) FROM Errors t1) as Count FROM Errors err) as errors) AS LogWithRowNumbers WHERE  Row >= @start AND Row <= @stop";
      command.Parameters.AddWithValue("@start", numPerPage * (page - 1));
      command.Parameters.AddWithValue("@stop", numPerPage * (page));

      if (app.HasValue)
      {
        command.CommandText += " AND Application = @app";
        command.Parameters.AddWithValue("@app", app.Value);
      }
      return command;
    }
  }
}
